package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"golang.org/x/net/websocket"
	"log"
	"message"
	"net/http"
	"strings"
	"time"
)

var (
	token       string
	firstTaskId string   = "1"
	ids         []string // message ids, use to set message read
	firstPlanId string
)

const (
	account  = "1"
	password = "123456"
	server   = "http://106.185.40.107:4001"
	origin   = "http://localhost/"
	ws       = "ws://localhost:4001/ws"
)

func login() {
	client := &http.Client{Timeout: time.Second * 10}
	req, err := http.NewRequest("GET", server+"/login", nil)
	// ...
	req.Header.Add("account", account)
	req.Header.Add("password", password)

	resp, err := client.Do(req)
	if err != nil {
		log.Fatal("login failed:", err)
	}

	if resp.StatusCode != 200 {
		log.Fatal("login failed:", resp.Status)
	}

	token = resp.Header.Get("tk")
	log.Println("login ok, tk:", token)
}

func receive(ws *websocket.Conn) {
	message := []byte("hello, world!")
	_, err := ws.Write(message)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Send: %s\n", message)
	var msg = make([]byte, 1024)
	for {
		_, err = ws.Read(msg)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("Receive: %s\n", msg)
	}
}

func webSocketIt() {
	config, err := websocket.NewConfig(ws, origin)
	if err != nil {
		log.Fatal(err)
		return
	}
	myToken := []string{token}
	config.Header["tk"] = myToken

	ws, err := websocket.DialConfig(config)
	if err != nil {
		log.Fatal(err)
	}
	go receive(ws)
}

func loadTask() {
	client := &http.Client{Timeout: time.Second * 10}
	req, err := http.NewRequest("GET", server+"/loadTasks", nil)
	// ...
	req.Header.Add("tk", token)

	resp, err := client.Do(req)
	if err != nil {
		log.Fatal("loadTask failed:", err)
	}

	if resp.StatusCode != 200 {
		log.Fatal("loadTask failed:", resp.Status)
	}

	errcode := resp.Header.Get("error")
	if errcode != "" {
		log.Fatal("startTask failed, error code:", errcode)
	}

	body := make([]byte, 1024)
	read, err := resp.Body.Read(body)
	if err != nil && read < 1 {
		log.Fatal("loadTask failed:", err)
	}

	body = body[:read]
	log.Println("loadTask ok, body:", string(body))

	if read < 1 {
		log.Println("no task loaded, please config task via web first")
		return
	}

	//var tasks []*tasks.Task
	//err = json.Unmarshal(body, &tasks)
	//if err != nil {
	//	log.Fatal("loadTask failed:", err)
	//}

	//firstTaskId = tasks[0].Id
}

func starTask() {
	client := &http.Client{Timeout: time.Second * 10}
	req, err := http.NewRequest("GET", server+"/startTask", nil)

	log.Printf("start task: %s", firstTaskId)
	req.Header.Add("tk", token)
	req.Header.Add("taskId", firstTaskId)

	resp, err := client.Do(req)
	if err != nil {
		log.Fatal("startTask failed:", err)
	}

	if resp.StatusCode != 200 {
		log.Fatal("startTask failed:", resp.Status)
	}

	errcode := resp.Header.Get("error")
	if errcode != "" {
		log.Fatal("startTask failed, error code:", errcode)
	}

	errcount := resp.Header.Get("errcount")
	log.Println("startTask ok, errcount:", errcount)
}

func stopTask() {
	client := &http.Client{Timeout: time.Second * 10}
	req, err := http.NewRequest("GET", server+"/stopTask", nil)
	// ...
	req.Header.Add("tk", token)
	req.Header.Add("taskId", firstTaskId)

	resp, err := client.Do(req)
	if err != nil {
		log.Fatal("stopTask failed:", err)
	}

	if resp.StatusCode != 200 {
		log.Fatal("stopTask failed:", resp.Status)
	}

	errcode := resp.Header.Get("error")
	if errcode != "" {
		log.Fatal("stopTask failed, error code:", errcode)
	}

	errcount := resp.Header.Get("errcount")
	log.Println("stopTask ok, errcount:", errcount)
}

func loadMsg() {
	client := &http.Client{Timeout: time.Second * 10}
	req, err := http.NewRequest("GET", server+"/loadMsg", nil)

	req.Header.Add("tk", token)

	resp, err := client.Do(req)
	if err != nil {
		log.Fatal("loadMsg failed:", err)
	}

	if resp.StatusCode != 200 {
		log.Fatal("loadMsg failed:", resp.Status)
	}

	errcode := resp.Header.Get("error")
	if errcode != "" {
		log.Fatal("loadMsg failed, error code:", errcode)
	}

	body := make([]byte, 1024*2)
	read, err := resp.Body.Read(body)
	if err != nil && read < 1 {
		log.Fatal("loadMsg failed:", err)
	}

	body = body[:read]
	log.Println("loadMsg ok, body: ", string(body))

	var strMsgs string
	err = json.Unmarshal(body, &strMsgs)
	if err != nil {
		log.Fatal("Unmarshall failed:", err)
	}

	var msgs []message.Message
	err = json.Unmarshal([]byte(strMsgs), &msgs)
	if err != nil {
		log.Fatal("Unmarshall failed:", err)
	}

	ids = make([]string, len(msgs))
	for index, msg := range msgs {
		ids[index] = fmt.Sprintf("%d", msg.Id)
	}

	log.Println("loadMsg ok, msgs:", msgs)

	if read < 1 {
		log.Println("no task loaded, please config task via web first")
		return
	}

}

func setReadMsg() {

	if length := len(ids); length < 1 {
		return
	}

	b, err := json.Marshal(ids)
	if err != nil {
		log.Printf("marshal err: ", err)
	}

	var _ = fmt.Printf
	var _ = strings.Join
	client := &http.Client{Timeout: time.Second * 10}
	req, err := http.NewRequest("GET", server+"/setReadMsg", bytes.NewBuffer(b))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Add("tk", token)

	resp, err := client.Do(req)
	if err != nil {
		log.Fatal("setReadMsg failed:", err)
	}

	if resp.StatusCode != 200 {
		log.Fatal("setReadMsg failed:", resp.Status)
	}

	errcode := resp.Header.Get("error")
	if errcode != "" {
		log.Fatal("setReadMsg failed, error code:", errcode)
	}

	errcount := resp.Header.Get("errcount")
	if errcount != "" {
		log.Println("stopTask ok, errcount:", errcount)
		return
	}
	log.Println("set read message success")
}

type OperationTime struct {
	StartTime uint64 `json:"starttime"`
	Duration  uint64 `json:"duration"`
}

func createPlan() {
	/*
		plan := plans.Plan{}
		plan.PlanId = "123456798"
		plan.PlanName = "plan-2"
		plan.Account = "account"
		plan.TaskIds = []string{firstTaskId}
		plan.StartTime = 14*60 + 15
		plan.Day = 1
		plan.DayType = 1
		plan.State = 0

		b, err := json.Marshal(plan)
		if err != nil {
			log.Printf("marshal err: ", err)
		}

		client := &http.Client{Timeout: time.Second * 10}
		req, err := http.NewRequest("GET", server+"/createPlan", bytes.NewBuffer(b))

		req.Header.Set("Content-Type", "application/json")
		req.Header.Add("tk", token)

		resp, err := client.Do(req)
		if err != nil {
			log.Fatal("createPlan failed:", err)
		}

		if resp.StatusCode != 200 {
			log.Fatal("createPlan failed:", resp.Status)
		}

		errcode := resp.Header.Get("error")
		if errcode != "" {
			log.Fatal("createPlan failed, error code:", errcode)
		}

		errcount := resp.Header.Get("errcount")
		if errcount != "" {
			log.Println("createPlan ok, errcount:", errcount)
			return
		}
		log.Println("create plan message success")
	*/
}

func loadPlan() {
	client := &http.Client{Timeout: time.Second * 10}
	req, err := http.NewRequest("GET", server+"/loadPlan", nil)
	// ...
	req.Header.Add("tk", token)

	resp, err := client.Do(req)
	if err != nil {
		log.Fatal("loadPlan failed:", err)
	}

	if resp.StatusCode != 200 {
		log.Fatal("loadPlan failed, StatusCode:", resp.Status)
	}

	errcode := resp.Header.Get("error")
	if errcode != "" {
		log.Fatal("startTask failed, error code:", errcode)
	}

	body := make([]byte, 1024)
	read, err := resp.Body.Read(body)
	if err != nil && read < 1 {
		log.Fatal("loadPlan failed, read err:", err)
	}

	body = body[:read]
	log.Println("loadPlan ok, body:", string(body))

	if read < 1 {
		log.Println("no task loaded, please config task via web first")
		return
	}

	//var plans []plans.Plan
	//err = json.Unmarshal(body, &plans)
	//if err != nil {
	//	log.Fatal("loadPlan failed:", err)
	//}

	//firstPlanId = plans[0].PlanId
	//log.Printf("plans: %v", plans)
}

func startPlan() {
	client := &http.Client{Timeout: time.Second * 10}
	req, err := http.NewRequest("GET", server+"/startPlan", nil)
	// ...
	req.Header.Add("tk", token)
	req.Header.Add("planId", firstPlanId)

	resp, err := client.Do(req)
	if err != nil {
		log.Fatal("startPlan failed:", err)
	}

	if resp.StatusCode != 200 {
		log.Fatal("startPlan failed:", resp.Status)
	}

	errcode := resp.Header.Get("error")
	if errcode != "" {
		log.Fatal("startPlan failed, error code:", errcode)
	}

	errcount := resp.Header.Get("errcount")
	log.Println("startPlan ok, errcount:", errcount)
}

func stopPlan() {
	client := &http.Client{Timeout: time.Second * 10}
	req, err := http.NewRequest("GET", server+"/stopPlan", nil)
	// ...
	req.Header.Add("tk", token)
	req.Header.Add("planId", firstPlanId)

	resp, err := client.Do(req)
	if err != nil {
		log.Fatal("stopPlan failed:", err)
	}

	if resp.StatusCode != 200 {
		log.Fatal("stopPlan failed:", resp.Status)
	}

	errcode := resp.Header.Get("error")
	if errcode != "" {
		log.Fatal("stopPlan failed, error code:", errcode)
	}

	errcount := resp.Header.Get("errcount")
	log.Println("stopPlan ok, errcount:", errcount)
}

func deletePlan() {
	client := &http.Client{Timeout: time.Second * 10}
	req, err := http.NewRequest("GET", server+"/deletePlan", nil)
	// ...
	req.Header.Add("tk", token)
	req.Header.Add("planId", firstPlanId)

	resp, err := client.Do(req)
	if err != nil {
		log.Fatal("deletePlan failed:", err)
	}

	if resp.StatusCode != 200 {
		log.Fatal("deletePlan failed:", resp.Status)
	}

	errcode := resp.Header.Get("error")
	if errcode != "" {
		log.Fatal("deletePlan failed, error code:", errcode)
	}

	errcount := resp.Header.Get("errcount")
	log.Println("deletePlan ok, errcount:", errcount)
}

func excCmd() {
	var cmd string
	for {
		_, err := fmt.Scanf("%s\n", &cmd)
		if err != nil {
			//log.Println("Scanf err:", err)
			continue
		}

		switch cmd {
		case "exit", "quit":
			log.Println("exit by user")
			return
		case "startTask":
			starTask()
			break
		case "stopTask":
			stopTask()
		default:
			break
		}
	}

	return
}

func createAccount(account string, password string) {
	//var rconn = rhelper.Pool().Get()
	//defer rconn.Close()

	//_, err := rconn.Do("HMSET", rhelper.AccountPrefix+account, "id", account, "password", password)
	//if err != nil {
	//	log.Println("create account err%s", err)
	//}

}

func createTask() {
	/*	var rconn = rhelper.Pool().Get()
		defer rconn.Close()

		task := tasks.Task{}
		task.Type = "water"
		task.Id = "1234567889"
		task.Name = "task-1"
		task.Duration = 10
		task.Account = "riguang"
		task.GwId = 1232323
		rconn.Send("MULTI")
		rconn.Send("HMSET", rhelper.TaskPrefix+task.Id, "type", task.Type, "id", task.Id, "name", task.Name,
			"duration", task.Duration, "account", task.Account, "gwId", task.GwId)
		rconn.Send("SADD", rhelper.AccountTaskPrefix+task.Account, task.Id)
		result, err := rconn.Do("EXEC")
		if err != nil {
			log.Println("create task err%s", err)
		} else {
			log.Println("create task: %v", result)
		}
	*/
}

func main() {
	//createAccount("riguang", "123456")
	//createTask()
	login()
	//webSocketIt()
	//loadTask()
	//excCmd()
	starTask()
	//excCmd()
	//stopTask()
	//loadMsg()
	//setReadMsg()
	//createPlan()
	//loadPlan()
	//startPlan()
	//stopPlan()
	//deletePlan()

}
